<template>
    <view class="form"><slot></slot></view>
</template>

<script>
import { deepCopy } from '../utils/util.js'

export default {
    name: 'uxt-form',
    data() {
        return {
            formId: Math.random(),
            initValues: {},
            values: {}
        }
    },
    provide() {
        return {
            formId: this.formId
        }
    },
    created() {
        uni.$on(`forminit.${this.formId}`, res => {
            this.initValues[res.id] = deepCopy(res)
            this.values = deepCopy(this.initValues)
        })
        uni.$on(`formchange.${this.formId}`, res => {
            this.values[res.id] = res
        })
        uni.$on(`formsubmit.${this.formId}`, () => {
            let values = {}
            let nameCount = {}
            for (let id of Object.keys(this.values)) {
                let item = this.values[id]
                if (values[item.name] === undefined || !item.merge) {
                    values[item.name] = item.value
                } else {
                    if (nameCount[item.name] === 1) {
                        values[item.name] = [values[item.name]]
                    }
                    values[item.name].push(item.value)
                }
                nameCount[item.name] =
                    nameCount[item.name] === undefined ? 1 : nameCount[item.name] + 1
            }
            this.$emit('submit', values)
        })
        uni.$on(`formreset.${this.formId}`, () => {
            uni.$emit(`reset.${this.formId}`, this.initValues)
            this.$emit('reset')
        })
    },
    destroyed() {
        uni.$off(`forminit.${this.formId}`)
        uni.$off(`formchange.${this.formId}`)
        uni.$off(`formsubmit.${this.formId}`)
        uni.$off(`formreset.${this.formId}`)
    }
}
</script>

<style lang="scss" scoped>
.form {
    // display: inline-block;
    position: relative;
}
</style>
